import jsonpath


class GetKeyword:
    @staticmethod
    def get_keyword(source_data, keyword, th=None):   # th用于选择第几个找到的数据，不填默认输出全部
        if th:
            # 如果填入的th过大，自动选择数据中最后一个
            if th > len(jsonpath.jsonpath(source_data, f'$..{keyword}')):
                print('所选位数超过找到个数，自动选择最后一个')
                return jsonpath.jsonpath(source_data, f'$..{keyword}')[0]
            return jsonpath.jsonpath(source_data, f'$..{keyword}')[int(f'-{th}')]
        else:
            return jsonpath.jsonpath(source_data, f'$..{keyword}')




# import requests
#
# res = requests.post(url='http://47.108.206.100:8080/admin/login',json={
#   "password": "macro123",
#   "username": "admin"
# })
# print(res.json())

if __name__ == '__main__':
    data = {'code': 200, 'message': '操作成功', "tokenHead": "123", 'data': {'tokenHead': 'Bearer ',
                                                                             'token': 'eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbiIsImNyZWF0ZWQiOjE2ODY1NTg2MDA3NTcsImV4cCI6MTY4NzE2MzQwMH0.w0-e8qC8W7W_u3ysZfHUVqp8tVj06ksSwfJfR0r9Z5_oErB_zvGfWT4AsEXA1WE7OQ1SnkfhmBFiKcgoblGQmg'}}

    print(GetKeyword.get_keyword(data,'tokenHead',4))
